﻿using FangChanCrm.Services.Interface;
using FangChanCrmModel;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Data;
using System.IO;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
//using Spire.Xls;
using Nancy.Json;
using System.Text.RegularExpressions;
using Maticsoft.Model;
using Microsoft.AspNetCore.Http;
using System.Text;
using Newtonsoft.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using FangChanCrmEF;

namespace FangChanCrm.Controllers
{
    public class KeHuZiYuanChiController : Controller
    {
        private readonly It_KeHuZiYuanChiService t_KeHuZiYuanChiService;
        private readonly It_RenYuanBiaoService It_RenYuanBiaoService;

        public KeHuZiYuanChiController(It_KeHuZiYuanChiService keHuZiYuanChiService, It_RenYuanBiaoService it_RenYuanBiaoService, IConfiguration configuration)
        {
            t_KeHuZiYuanChiService = keHuZiYuanChiService;
            It_RenYuanBiaoService = it_RenYuanBiaoService;
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
       
        public IActionResult KeHuZiYuanChiList()
        {
            if (HttpContext.Session.GetString("loginid") == null)
            {
                HttpContext.Request.Cookies.TryGetValue("账户", out string value);
                if (value == null || value == "")
                {
                    return View("../Login/Login");
                }
                else
                {
                    return View("../Login/LoginChongXin");
                }
            }
            else
            {
                return View();
            }
        }
        public IActionResult PhoneKeHuZiYuanChi()
        {
            if (HttpContext.Session.GetString("loginid") == null)
            {
                HttpContext.Request.Cookies.TryGetValue("账户", out string value);
                if (value == null || value == "")
                {
                    return View("../Login/Login");
                }
                else
                {
                    return View("../Login/LoginChongXin");
                }
            }
            else
            {
                return View();
            }
        }
        public IActionResult YiFenPei()
        {
            if (HttpContext.Session.GetString("loginid") == null)
            {
                HttpContext.Request.Cookies.TryGetValue("账户", out string value);
                if (value == null || value == "")
                {
                    return View("../Login/Login");
                }
                else
                {
                    return View("../Login/LoginChongXin");
                }
            }
            else
            {
                return View();
            }
        }
        public string KeHuZiYuanChiFenYe()
        {
            string YuanGongMingCheng = Request.Form["YuanGongMingCheng"].ToString();
            t_KeHuZiYuanChi t_KeHuZiYuanChi = new t_KeHuZiYuanChi();
            t_KeHuZiYuanChi.RenYuanId = Convert.ToInt32(YuanGongMingCheng);
            string shuju = t_KeHuZiYuanChiService.GetListWithFenYe(t_KeHuZiYuanChi, Convert.ToInt32(Request.Form["start"]), Convert.ToInt32(Request.Form["limit"]));
            if (t_KeHuZiYuanChiService.listshuju().ToList().Count != 0)
            {
                return shuju;
            }
            else
            {
                string jsonString = "{\"draw\":1,\"total\":0,\"total\":0,";
                jsonString += "\"" + "data" + "\":" + "[]" + ",";
                jsonString = jsonString.TrimEnd(',');
                return jsonString + "}";
                //return "[]";
            }
        }

        public string ZiYuanChiFenPeiList()
        {
            int id = Convert.ToInt32(HttpContext.Session.GetString("UserId"));
            List<t_KeHuZiYuanChi> list = t_KeHuZiYuanChiService.GetList2(id);
            string json = "[";
            for (int i = 0; i < list.Count; i++)
            {
                json += "{";
                json += "\"LianXiFangShi\":\"" + list[i].ShouJiHao + "\",\"Id\":\"" + list[i].Id + "\"";
                json += "}";
                if (i != list.Count - 1)
                {
                    json += ",";
                }
            }
            json += "]";
            return json;
        }

        public string ShanChuFangFaH()
        {
            string Id = Request.Form["Shuju"].ToString();

            bool panduan = false;
            var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
            optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            using (var _context = new MyContext(optionsBuilder.Options))
            {
                var KeHuZiYuanChi = _context.t_KeHuZiYuanChi.FirstOrDefault(x => x.Id == Convert.ToInt32(Id));
                KeHuZiYuanChi.ZhuangTai = "已作废";
                panduan = _context.SaveChanges() > 0;
            }

            if (panduan)
            {
                return "1";
            }
            else
            {
                return "0";
            }
        }
        public string YiFenPeiFenYe()
        {
            string YuanGongMingCheng = Request.Form["YuanGongMingCheng"].ToString();
            t_KeHuZiYuanChi t_KeHuZiYuanChi = new t_KeHuZiYuanChi();
            t_KeHuZiYuanChi.RenYuanId = Convert.ToInt32(YuanGongMingCheng);
            string shuju = t_KeHuZiYuanChiService.YiFenPeiFenYe(t_KeHuZiYuanChi, Convert.ToInt32(Request.Form["start"]), Convert.ToInt32(Request.Form["limit"]));
            if (t_KeHuZiYuanChiService.listshuju().ToList().Count != 0)
            {
                return shuju;
            }
            else
            {
                string jsonString = "{\"draw\":1,\"total\":0,\"total\":0,";
                jsonString += "\"" + "data" + "\":" + "[]" + ",";
                jsonString = jsonString.TrimEnd(',');
                return jsonString + "}";
                //return "[]";
            }
        }
        public string BangDingRenYuan()
        {
            //List<t_RenYuanBiao> list = It_RenYuanBiaoService.GetList();
            var list = It_RenYuanBiaoService.GetList();
            for (int i = 0; i < list.Count; i++)
            {
                list[i].t_BeiWangLus = null;
                list[i].t_GangWeiBiao = null;
                list[i].t_KeHuBiaos = null;
                list[i].t_KeHuZiYuanChis = null;
                list[i].t_RenYuanQuanXians = null;
                list[i].t_XiaoShouBiao_QueRenRens = null;
                list[i].t_XiaoShouBiao_YeWuYuans = null;
                list[i].t_XiaoShouBiao_ZhiYeGuWens = null;
                list[i].t_XiaoShouXiangXiBiao_CaoZuoRens = null;
                list[i].t_XiaoShouXiangXiBiao_QueRenDaoFangRens = null;
                list[i].t_XiaoXiTiXingBiaos = null;
                list[i].t_YiJianFanKuiBiaos = null;
                list[i].t_ZhanDuiBiao = null;
                list[i].t_ZhanQuBiao = null;
            }
            return JsonConvert.SerializeObject(list, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
            //StringBuilder Json = new StringBuilder();
            //Json.Append("[");
            //for (int i = 0; i < list.Count; i++)
            //{
            //    t_RenYuanBiao ry = list[i];
            //    Json.Append("{\"XingMing\":\"" + ry.XingMing + "\",\"Id\":\"" + ry.Id + "\" }");
            //    if ((i + 1) == list.Count)
            //    {

            //    }
            //    else
            //    {
            //        Json.Append(",");
            //    }
            //}
            //Json.Append("]");
            //return Json.ToString();
        }
        public string FenPeiKeHu()
        {
            string KeHuZiYuanChiId = Request.Form["KeHuZiYuanChiId"].ToString();
            int RenYuanId = Convert.ToInt32(Request.Form["RenYuanId"]);
            string[] sArray = KeHuZiYuanChiId.Split(",");
            for (int i = 0; i < sArray.Length; i++)
            {
                bool panduan = false;
                var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
                optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
                using (var _context = new MyContext(optionsBuilder.Options))
                {
                    var KeHuZiYuanChi = _context.t_KeHuZiYuanChi.FirstOrDefault(x => x.Id == Convert.ToInt32(sArray[i]));
                    KeHuZiYuanChi.RenYuanId = RenYuanId;
                    KeHuZiYuanChi.ZhuangTai = "已分配";
                    panduan = _context.SaveChanges() > 0;
                }
            }
            return "";
        }
        public string DaoRuExcel()
        {
            var shuju = Request.Form["shuju"].ToString();
            DataTable dt = JsonToDT(shuju);
            List<t_KeHuZiYuanChi> list = t_KeHuZiYuanChiService.GetList1();
            int shu = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                bool panduan = true;
                for (int j = 0; j < list.Count; j++)
                {
                    if (list[j].ShouJiHao == dt.Rows[i]["手机号"].ToString())
                    {
                        shu++;
                        panduan = false;
                        break;
                    }
                }
                if (panduan == true)
                {
                    t_KeHuZiYuanChi khzyc = new t_KeHuZiYuanChi();
                    khzyc.ShouJiHao = dt.Rows[i]["手机号"].ToString();
                    khzyc.ZhuangTai = "未分配";
                    t_KeHuZiYuanChiService.Add(khzyc);
                }
            }
            return "提交成功，重复手机号有" + shu + "个!";
        }
        public static DataTable JsonToDT(string strJson)
        {
            //转换json格式
            strJson = strJson.Replace(",\"", "*\"").Replace("\":", "\"#").ToString();
            //取出表名   
            var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
            string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //获取数据   
            rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split('*');

                //创建表   
                if (tb == null)
                {
                    tb = new DataTable();
                    tb.TableName = strName;
                    foreach (string str in strRows)
                    {
                        var dc = new DataColumn();
                        string[] strCell = str.Split('#');

                        if (strCell[0].Substring(0, 1) == "\"")
                        {
                            int a = strCell[0].Length;
                            dc.ColumnName = strCell[0].Substring(1, a - 2);
                        }
                        else
                        {
                            dc.ColumnName = strCell[0];
                        }
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }

                //增加内容   
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    dr[r] = strRows[r].Split('#')[1].Trim().Replace("，", ",").Replace("：", ":").Replace("\"", "");
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }

            return tb;
        }

    }

}
